<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:34
 */

namespace app\home\controller;

use app\admin\model\Config;
use app\admin\model\Uploads;
use app\home\model\CreditRecord;
use app\home\model\Member;
use app\home\model\Sign;
use app\home\model\Task;
use app\home\model\TaskJoin;
use app\home\model\Withdraw;
use app\home\model\Recharge;
use think\Db;
use think\Log;
use think\Cache;
use app\admin\model\InvitationRebateRecord;

class Account extends Base{
    public $kc_money = 0;
    public $setting = [
    	    'invitation_one_rebate' => 0,
    	    'invitation_two_rebate' => 0,
    	    'invitation_three_rebate' => 0,
    	    'invitation_vip_one_rebate' =>0,
    	    'invitation_vip_two_rebate' =>0,
    	    'invitation_vip_three_rebate' =>0,
    	    'kc_money' =>0        
        ];
    
    public function _initialize()
    {
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['invitation_one_rebate'])){
                $this->setting['invitation_one_rebate'] = round(floatval($setting['invitation_one_rebate']/100),2);
            }
            if(!empty($setting['invitation_two_rebate'])){
                 $this->setting['invitation_two_rebate'] = round(floatval($setting['invitation_two_rebate']/100),2);
            }
            if(!empty($setting['invitation_three_rebate'])){
                 $this->setting['invitation_three_rebate'] = round(floatval($setting['invitation_three_rebate']/100),2);
            }
            if(!empty($setting['invitation_vip_one_rebate'])){
                 $this->setting['invitation_vip_one_rebate'] = round(floatval($setting['invitation_vip_one_rebate']/100),2);
            }
            if(!empty($setting['invitation_vip_two_rebate'])){
                 $this->setting['invitation_vip_two_rebate'] = round(floatval($setting['invitation_vip_two_rebate']/100),2);
            }
            if(!empty($setting['invitation_vip_three_rebate'])){
                 $this->setting['invitation_vip_three_rebate'] = round(floatval($setting['invitation_vip_three_rebate']/100),2);
            }	 
            if(!empty($setting['kc_money'])){
                 $this->setting['kc_money'] = round(floatval($setting['kc_money']/100),2);
            }	            
        } 	
    }    
    
	public function defr_pet(){
		$new = [];
		$result = db('member1')->field('uid,pet_num')->select();
		foreach ($result as $k=> $v){
			$res = db('member')->where('uid',$v['uid'])->value('pet_num');
			if($v['pet_num'] !=$res){

				$new[$k] = ['uid'=>$v['uid'],'qian'=>$v['pet_num'],'hou'=>$res];
			}
		}
		var_dump($new);
		
	}
	//红包
	public function hongbao(){
	    $list = db('redpackage')->where('is_over',0)->order('money DESC')->select();
	    foreach ($list as $k=>$v){
	        $member = db('member')->where('uid',$v['uid'])->find();
	        $task = db('Task')->where('id',$v['task_id'])->find();
	        $list[$k]['touxiang'] = $member['avatar']?$member['avatar']:'/static/home/mobile/picture/user.png';
	        $list[$k]['nickname'] = $member['nickname'];
	        $list[$k]['title'] = $task['title'];
	    }
	    return $this->fetch(__FUNCTION__,[
            'list' => $list
        ]);
	}
	//每周一跑用户完成任务最多的前50名记录在数据库
    public function renwu_jl(){
    	$date = time()-3600*24*7;
    	$money = 0;
    	$id = 1;
    	$result = db('task_join')->where('create_time','>',$date)->where('status',3)->field('uid,count(id) as nnum')->order('count(id) desc')->group('uid')->limit(50)->select();
    	foreach ($result as $value){
    		db('renwu_ph')->where('id',$id)->update(['uid'=>$value['uid'],'num'=>$value['nnum']]);
    		$id++;
    	}
    	$res = db('renwu_ph')->select();
    	foreach ($res as $v){
    		$data = db('task_join')->where('uid',$v['uid'])->where('create_time','>',$date)->where('status',3)->select();
    		foreach ($data as $vv){
    			$money+=db('task')->where('id',$vv['task_id'])->value('unit_price');
    		}
    		db('renwu_ph')->where('uid',$v['uid'])->setField('money',$money);
    		$username = db('member')->where('uid',$v['uid'])->value('nickname');
    		db('renwu_ph')->where('uid',$v['uid'])->setField('username',$username);
    		$money = 0;
    		
    	}
    }
    //做任务排行页面
    public function renwu_ph(){
    	$list = db('renwu_ph')->select();
    	/*foreach($list as $p){
        		$p['nickname']=$this->get_nickname($p['nickname']);
        }*/
        return $this->fetch(__FUNCTION__,[
            'list' => $list
        ]);
    }

       public function index(){
        $member = $this->checkLogin();

        $complaint_num = db('complaint')->where('fid',$member['uid'])->where('status',0)->count();
        $is_sign = Sign::getTodayInfoByUid($member['uid']);

        if(request()->isAjax()){
            if(!empty($is_sign)){
                message('今日已签到','','error');
            }
            $config = Config::getInfo();
            $sign_credit1 = 0.1;
            // if(!empty($config['setting']['sign_give_credit1'])){
            //     $sign_credit1 = floatval(trim($config['setting']['sign_give_credit1']));
            // }
            // if($sign_credit1 <= 0){
            //     message('平台未开启签到送积分','','error');
            // }
           if($member->level > 1){
               $sign_credit1 = 1;
           }
            Db::startTrans();
            // $status1= Member::updateInfoById($member['uid'],[
            //     'credit1' => $member['credit1']+$sign_credit1,
            //     'pet_need_credit'=>$member['pet_need_credit']+$sign_credit1
            // ]);
            $status1= Member::updateInfoById($member['uid'],[
                'credit2' => $member['credit2']+$sign_credit1
            ]);            
            if(!$status1){
                Db::rollback();
                message('签到失败：-1','','error');
            }
            $status2 = Sign::addInfo([
                'uid' => $member['uid'],
                'credit1' => $sign_credit1
            ]);
            if(!$status2){
                Db::rollback();
                message('签到失败：-2','','error');
            }
            $status3 = CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit2',
                'num' => $sign_credit1,
                'title' => '签到',
                'remark' => "签到成功，获得{$sign_credit1}元。"
            ]);
            if(!$status3){
                Db::rollback();
                message('签到失败：-3','','error');
            }
            Db::commit();
            message("签到成功，+{$sign_credit1}元",'reload','success');            
            // $status3 = CreditRecord::addInfo([
            //     'uid' => $member['uid'],
            //     'type' => 'credit1',
            //     'num' => $sign_credit1,
            //     'title' => '签到',
            //     'remark' => "签到成功，获得{$sign_credit1}积分。"
            // ]);
            // if(!$status3){
            //     Db::rollback();
            //     message('签到失败：-3','','error');
            // }
            // Db::commit();
            // message("签到成功，+{$sign_credit1}积分",'reload','success');
        }
        //发布次数
        $task_num = Task::getTotalCountByMemberId($member['uid']);
        //参与次数
        $join_num = TaskJoin::getTotalCountByMemberId($member['uid']);
        
        //审核次数
        // $params = array();
        // $params['uid'] = $member['uid'];
        // $params['category_type'] = "audit";
        // $audit_num = \app\home\model\MyTask::getCountByParams($params);
        
        $levels = Db::name("member")->where("uid = {$this->member->uid}")->find();
        $msg_level = Db::name("member_level")->where("level = {$levels['level']}")->find();
        
        
		//待审核的数量
        $audit_num=$task_ids = \db('task_join')->alias('n')->join("tb_task m","m.id=n.task_id")->where(['m.uid'=>$member['uid'],'m.out_stock_flag'=>0,'m.is_complete'=>0,'n.status'=>2])->count();
		
        
        return $this->fetch(__FUNCTION__,[
            'member' => $member,
            'msg_levels'=>$msg_level['title'],
            'task_num' => $task_num,
            'join_num' => $join_num,
            'audit_num' => $audit_num,
            'is_bind_weixin'=>$member['openid2']?1:'',
            'is_sign' => !empty($is_sign)?1:0,
            'complaint_num' => $complaint_num
        ]);
    }
    
    
    //绑定微信openid
    public function bind_wx(){
        $member = $this->checkLogin();
        $config = Config::getInfo();
         if($member['openid']){
            header('Location:'.$config['setting']['yuming'].'/index/one');die;
         }
         $openid_info = db('member')->where('openid',input('openid'))->find();
            if($openid_info){
                header('Location:'.$config['setting']['yuming'].'/index/two');die;
            }
         $res = db('member')->where('uid',$member['uid'])->setField('openid',input('openid'));
         if($res){
            header('Location:'.$config['setting']['yuming'].'/index/three');
         }else{
            header('Location:'.$config['setting']['yuming'].'/index/four');
         }
    }
    public function myaccount(){
        $member = $this->checkLogin();
        return $this->fetch(__FUNCTION__,[
            'member'=>$member
        ]);
    }
  public function upname(){
      if(request()->isAjax()){
          $params = request()->post();
          if(!empty($params))
          {
              $status= Member::updateInfoById($params['uid'],['nickname'=>$params['nickname']]);
              if(!$status)
              {
                  message('填写失败','','error');
              }
              else
              {
                  message('填写成功！','reload','success');
              }
          }
      }
  }
  
      public function bind_weixin(){
         $member = $this->checkLogin();
       
         if(!request()->isAjax()){
         		die;
         }
         
         if($member['openid2']){
         	 message('该账号已绑定微信！','reload','error');
         }
         $request=request();
         $openid=$request->param('openid');
         $access_token=$request->param('access_token');
         if(!$openid || !$access_token){
         	 message('登录错误！','','error');
         }
         
         if(!$member['openid2']){

         $is_bind=db('member')->where('openid2',$openid)->find();
         if($is_bind){
         	 message('该微信已绑定其他账户！','','error');
         }

         //验证openid有效性
         $controller=controller('wx');
         //$data=$controller->get_access_token($code); //获取网页授权access_token和用户openid
         $data_all = $controller->get_user_info($access_token,$openid);//获取微信用户信息
         if(empty($data_all['openid'])){
         	 message('系统错误！','','error');
         }
            $user_data=[
                'openid2'=>$openid,
                'nickname'=>$request->param('nickname'),
                'gender'=>$request->param('sex'),
                'avatar'=>$request->param('headimgurl'),
                'uid'=>$member['uid']
            ];
            $res=db('member')->update($user_data);
            if($res){
                    // to_json(1, '绑定微信成功！', []);
                    
	         	//绑定微信给上级奖励
	         	if($member['parent_uid']){
	         		
			         	$credit2 = 0.5;
			            $status1 = Member::updateCreditById($member['parent_uid'], 0, $credit2);
			 
			            $status2 = CreditRecord::addInfo([
			                'uid' => $member['parent_uid'],
			                'type' => 'credit2',
			                'num' => $credit2,
			                'title' => '徒弟'.$member['uid'].'绑定微信奖励',
			                'remark' =>'徒弟'.$member['uid'].'绑定微信,奖励0.5元.',
			                'create_time' => TIMESTAMP
			            ]);
			            
			            //添加纪录
                		InvitationRebateRecord::addInfo([
                            'uid' => $member['parent_uid'],
                            'num' => $credit2,
                            'task_id' => 0,
                            'tuijian_id' =>$member['uid'],
                            'remark' => "徒弟[" . $member['uid'] . "]绑定微信成功，获得推荐收入{$credit2}元.。",
                            'create_time' => TIMESTAMP
                        ]);
			            
			            
	         	}
                    
                    
                     message('绑定微信成功！','reload','success');
            }else{
                     to_json(0, '绑定微信失败！', []);
                    message('绑定微信失败','reload','error');

            }
         }
    }
 

  
    public function info(){
        $member = $this->checkLogin();

        if(request()->isAjax()){
            //一周只能换一次
            if($member['atvar_time']>strtotime('-7 days')){
                message('头像每周可修改一次','','error');
            }
            
            $file = request()->file('avatar');
          
            $info = $this->qiniuupload($file);
            if(!$info){
                message('图片错误','','error');
            }
            $member_data['avatar'] = 'http://'.$info;
            $member_data['atvar_time'] = time();
            $status = db('member')->where('uid',$member['uid'])->update($member_data);
            if(!$status){
                message('头像修改失败','','error');
            }
            message('头像修改成功','reload','success');
        }
        return $this->fetch(__FUNCTION__,[
            'member' => $member
        ]);
    }
  
      public function info1(){
        $member = $this->checkLogin();
        if(request()->isAjax()){
            $file = request()->file('avatar');
             /*$config = [
                'size' => 2097152,
                'ext'  => 'jpg,gif,png,bmp,heic,HEIC'
            ];*/
            // 移动到框架应用根目录/public/uploads/ 目录下
            //$info = $file->validate($config)->move(ROOT_PATH . 'public' . DS . 'uploads');
          
            $info = $this->qiniuupload($file);
            if(!$info){
                message('图片错误','','error');
            }
            $record = [
                'uid' => $member['uid'],
                'extension' => substr($info,strpos($info,'.')+1),
                'save_name' => $info,
                'filename' => config('BUCKET'),
                'md5' => md5($info),
                'sha1' => 123,
                'size' => '11',
                'create_time' => TIMESTAMP
            ];
            //数据库存入失败记录日志
            if(!Uploads::addInfo($record)){
                Log::error(__FILE__.':'.__LINE__.' 错误：'.$record['save_name'].'数据库记录失败');
            }
            $status = Member::updateInfoById($member['uid'],['avatar'=>$record['save_name']]);
            if(!$status){
                message('头像修改失败','','error');
            }
            message('头像修改成功','reload','success');
        }
        return $this->fetch(__FUNCTION__,[
            'member' => $member
        ]);
    }

 public function withdraw(){
        $member = $this->checkLogin();
        $config = Config::getInfo();
        $sett = $config['setting'];
        /*if($member['auth']==0){
            $this->redirect('/home/account/check_name.html');
        }*/
        if($member['level']>1){
        	$setting = ['withdraw_min' => 1, 'withdraw_fee' => $sett['withdraw_fee_member']];
        }
        if($member['level']<=1){
        	$setting = ['withdraw_min' => 1, 'withdraw_fee' => $sett['withdraw_fee']];
        }
        
        
      

        if(request()->isAjax()){
            $params = request()->post();
            $result = $this->validate($params,'Withdraw');
            if($result !== true){
                message($result,'','error');
            }
            
            if($params['credit2']>1000){
                message('单次最高提现1000元','','error');
            }
            if($params['credit2'] < $setting['withdraw_min']){
                message('提现金额不能少于'.$setting['withdraw_min'].'元','','error');
            }
            

            //处理是整数的
            params_floor(['credit2'], $params);
            $params['fee'] = $params['credit2'] * ($setting['withdraw_fee'] / 100);
            $credit2 = ($params['credit2'] + $params['fee']);
            if($credit2 > $member['credit2']){
            	$canmoney = floor($member['credit2']/(1+$setting['withdraw_fee'] / 100));
                $feemoney=floor($member['credit2'] * ($setting['withdraw_fee'] / 100));
                message('最多可提现'.$canmoney.'元'.'包含手续费'.$feemoney.'元','','error');
            }
            
            // message('系统维护中...','','error');
            
            if($member['tx_day']==date('Ymd')){
                message('每天仅可提现一次','','error');
            }

            Db::startTrans();
            $status1 = Member::updateCreditById($member['uid'], 0, -$credit2);
            if(!$status1){
                Db::rollback();
                message('提现失败：-1','','error');
            }
            /*$statistics = Db::name('statistics')->where('time',date('Ymd'))->inc('tixian',$params['credit2'])->inc('tx_sx',$params['fee'])->update();
            if(!$statistics){
                Db::rollback();
                message('提现失败：-8','','error');
            }*/
            //记录提现操作
            $status2 = CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit2',
                'num' => -$credit2,
                'title' => '提现',
                'remark' => "申请提现到账号：" . $params['account'] . "，扣除{$credit2}余额。",
                'create_time' => TIMESTAMP
            ]);
            if(!$status2){
                Db::rollback();
                message('提现失败：-2','','error');
            }
          
            //记录提现单子
            $withdraw_data = [
                'uid' => $member['uid'],
                'username' => $member['username'],
                'credit2' => $params['credit2'],
                'fee' => $params['fee'],
                'pay_method' => $params['pay_method'],
                'realname' => $member['alipay_realname'],
                
                'create_time' => TIMESTAMP
            ];
            //判断是微信还是支付宝从而给出正确账号
            //微信
            if($params['pay_method']==2){
                if($member['wx_img']==''){
                    $file = request()->file('wx_img');
                    if(!$file){
                        message('请上传微信收款码','','error');
                    }
                  //七牛
                  $qninfo = $this->qiniuupload($file);
                  if(!$qninfo){
                         message('图片错误','','error');
                  }
                \db('member')->where(['uid'=>$member['uid']])->setField('wx_img','http://'.$qninfo);
                }
        		$withdraw_data['account'] = $params['account'];
		                if($member['tx_wx'] !=''){
		                    $withdraw_data['account'] = $member['tx_wx'];
		                }else{
		                    $withdraw_data['account'] = $params['account'];
		                    db('member')->where('uid',$member['uid'])->setField('tx_wx',$params['account']);
		                }
		                //完毕
            }else{     
            	 //支付宝
                if($member['alipay_account'] !=''){
                    $withdraw_data['account'] = $member['alipay_account'];
                }else{
                    $withdraw_data['account'] = $params['account'];
                    db('member')->where('uid',$member['uid'])->setField('alipay_account',$params['account']);
                }
                if($member['ali_img']==''){
                    $file = request()->file('ali_img');
                    if(!$file){
                        message('请上传支付宝收款码','','error');
                    }
                  //七牛
                  $qninfo = $this->qiniuupload($file);
                  if(!$qninfo){
                         message('图片错误','','error');
                  }
                \db('member')->where(['uid'=>$member['uid']])->setField('ali_img','http://'.$qninfo);
                }
            	
            	//判断该账号今天是否有人提现
                $today=strtotime(date('Ymd'));
                $withdraw_where=[
                    'account'=>$withdraw_data['account'],
                    'pay_method'=>1,
                    'create_time'=>['gt',$today],
                ];
                $has_withdraw=db('withdraw')->where($withdraw_where)->find();

                if($has_withdraw){
                        Db::rollback();
                        message('该支付宝账号今天已提现','','error');
                }
            }
            $status3 = Withdraw::addInfo($withdraw_data);
            
            if(!$status3){
                Db::rollback();
                message('提现失败：-3','','error');
            }
            
            //提现成功以后把提现日期做修改
            db('member')->where('uid',$member['uid'])->setField('tx_day',date('Ymd'));
            Db::commit();


            message('提现成功，请耐心等待平台审核，预计24小时内到帐','reload','success');
        }
        
        
        $type=input('type');
        if($type){
	        return $this->fetch('withdraw2',[
	            'member' => $member,
	            'setting' => $setting,
	            'qrurl'   => $config['setting']['yuming'].'/index/bind_login'
	        ]);
        }else{
        	 return $this->fetch(__FUNCTION__,[
	            'member' => $member,
	            'setting' => $setting,
	            'qrurl'   => $config['setting']['yuming'].'/index/bind_login'
	        ]);
        }

    }

    public function withdrawal(){
        return $this->fetch(__FUNCTION__);
    }

    public function wechatwithdrawal(){
        return $this->fetch(__FUNCTION__);
    }

    public function withdrawlog(){
        $member = $this->checkLogin();

        return $this->fetch(__FUNCTION__);
    }

    public function withdrawlog_ajax() {
        $member = $this->checkLogin();

        $where = ['uid' => $member['uid']];
        $list = \app\admin\model\Withdraw::getPagination($where, 15, NULL, "id DESC");

        to_json(0, '', $list);
    }


    public function credit(){
        $member = $this->checkLogin();

        return $this->fetch(__FUNCTION__);
    }

    public function credit_ajax() {
        $member = $this->checkLogin();

        $where = ['uid' => $member['uid'], 'type' => 'credit1'];
        $result = $this->getPagination('Charge', 20, $where, "id DESC", "*");

        to_json(0, '', $result['lists']);
    }

    public function task(){
        return $this->fetch(__FUNCTION__);
    }

    public function recharge(){
        $member = $this->checkLogin();

        if(request()->isAjax()){
            $params = request()->post();
            $result = $this->validate($params,'Recharge');
            if($result !== true){
                message($result,'','error');
            }
            if($params['credit2'] < 20){
                message('充值金额不能少于20元','','error');
            }

            //处理是整数的
            params_floor(['credit2'], $params);

            // 获取表单上传文件
            $thumbs = [];
            $files = request()->file('thumbs');
            $config = [
                'size' => 2097152,
                'ext'  => 'jpg,gif,png,bmp'
            ];
            if(check_array($files)){
                foreach($files as $file){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->validate($config)->move(ROOT_PATH . 'public' . DS . 'uploads');
                    if(!$info){
                        message($file->getError(),'','error');
                    }
                    $record = [
                        'uid' => $this->member['uid'],
                        'extension' => $info->getExtension(),
                        'save_name' => str_replace('\\','/',$info->getSaveName()),
                        'filename' => $info->getFilename(),
                        'md5' => $info->hash('md5'),
                        'sha1' => $info->hash('sha1'),
                        'size' => $info->getSize(),
                        'create_time' => TIMESTAMP
                    ];
                    //记录文件信息
                    array_push($thumbs,$record['save_name']);
                    //数据库存入失败记录日志
                    if(!Uploads::addInfo($record)){
                        Log::error(__FILE__.':'.__LINE__.' 错误：'.$record['save_name'].'数据库记录失败');
                    }
                }
            }
            $params['thumbs'] = isset($thumbs[0])?$thumbs[0]:'';

            Db::startTrans();
            $status3 = Recharge::addInfo([
                'uid' => $member['uid'],
                'username' => $member['username'],
                'credit2' => $params['credit2'],
                'realname' => $params['realname'],
                'account' => $params['account'],
                'pay_time' => $params['pay_time'],
                'thumbs' => $params['thumbs'],
                'create_time' => TIMESTAMP
            ]);
            if(!$status3){
                Db::rollback();
                message('提现失败：-3','','error');
            }
            Db::commit();

            message('提交成功，请耐心等待平台审核，预计24小时内到帐','reload','success');
        }
        return $this->fetch(__FUNCTION__,[
            'member' => $member
        ]);
    }

    public function rechargelog(){
        $member = $this->checkLogin();

        return $this->fetch(__FUNCTION__);
    }

    public function rechargelog_ajax() {
        $member = $this->checkLogin();

        $where = ['uid' => $member['uid']];
        $list = \app\admin\model\Recharge::getPagination($where, 15, NULL, "id DESC");

        to_json(0, '', $list);
    }
    //校验身份证和名字
    public function check_name(){
        $member = $this->checkLogin();


        if(request()->isAjax()){
            $idcard_info = db('member')->where('idcard',input('idcard'))->find();
            if($idcard_info){
                message('此身份证已被他人绑定','','error');
            }
            if($member['auth_num']>4){
                message('操作失败次数超过5次，无法绑定','','error');
            }
            $host = "http://idcard3.market.alicloudapi.com";
            $path = "/idcardAudit";
            $method = "GET";
            $appcode = "2aff5a9830b0469bbaabed2e7f1ee64e";
            $headers = array();
            array_push($headers, "Authorization:APPCODE " . $appcode);
            $querys = "idcard=".input('idcard')."&name=".input('realname');
            $bodys = "";
            $url = $host . $path . "?" . $querys;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            if (1 == strpos("$".$host, "https://"))
            {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $data = json_decode(curl_exec($curl),true);
            curl_close($curl);
            if($data['showapi_res_body']['code']==0){
                //验证ok
                $mdata['alipay_realname'] = input('realname');
                //$mdata['idcard']   = input('idcard');
                $mdata['idcard']   = '******************';
                $mdata['auth']     = 1;
                db('member')->where('uid',$member['uid'])->update($mdata);
                message('认证成功','/home/recharge.html','success');
            }else{
                db('member')->where('uid',$member['uid'])->setInc('auth_num');
                message('校验失败，请认真填写','reload','error');
            }
        }
        return $this->fetch(__FUNCTION__,[
            'member' => $member
        ]);
    }
    public function jifen(){
        $member = $this->checkLogin();
        $config = Config::getInfo();
        if(request()->isAjax()){
            if($member['auth'] !=1){
               // message('未完成实名认证无法获得奖励','reload','error');
            }
            if($member['avatar']==''){
                message('未上传头像无法获得奖励','reload','error');
            }
            if($member['over_task_num']<1){
                message('至少完成一次任务','reload','error');
            }
            if($member['rz_reward']==1){
                message('奖励只能领取一次','reload','error');
            }
            $data['credit1'] = $member['credit1']+$config['setting']['renzheng'];
            $data['credit2'] = $member['credit2']+$config['setting']['renzheng2'];
            $res = db('member')->where('uid',$member['uid'])->update($data);
            if($res){
                
                CreditRecord::addInfo([
                            'uid' => $member['uid'],
                            'type' => 'credit1',
                            'num' => $config['setting']['renzheng'],
                            'title' => '新手奖励',
                            'remark' => "领取成功，奖励".$config['setting']['renzheng']."积分。",
                            'create_time' => TIMESTAMP
                        ]);
                CreditRecord::addInfo([
                            'uid' => $member['uid'],
                            'type' => 'credit2',
                            'num' => $config['setting']['renzheng2'],
                            'title' => '新手奖励',
                            'remark' => "领取成功，奖励".$config['setting']['renzheng2']."元。",
                            'create_time' => TIMESTAMP
                        ]);
                $credit['rz_reward']= 1;
                $credit['pet_need_credit']= $member['pet_need_credit']+$config['setting']['renzheng'];
                db('member')->where('uid',$member['uid'])->update($credit);
                message('领取成功','/home/account.html','success');
            }

        }
      
        //有效好友个数
        $down=db('member')->where('parent_uid',$member['uid'])->column('uid');
        $valid_count=db('withdraw')->where(['uid'=>['in',$down]])->count();
        return $this->fetch(__FUNCTION__,[
            'member' => $member,
            'jiangli'=>$config['setting']['renzheng'],
            'valid_count'=>$valid_count
        ]);
    }
  
  public function get_reward(){
  	$member = $this->checkLogin();
  	$type=input('type');
  	if($type == 'is_share'){
  		if($member['is_share'] == 2){
  			message('您已领取过奖励，不能重复领取','reload','error');
  		}
  		if($member['is_share'] == 1){
  			//增加用户余额
  			$data['credit2'] = $member['credit2']+0.1;
  			$data['is_share']=2;
  			  $res = db('member')->where('uid',$member['uid'])->update($data);
  			  if($res){
  			  	
		        	CreditRecord::addInfo([
		                    'uid' => $member['uid'],
		                    'type' => 'credit2',
		                    'num' => 0.1,
		                    'title' => '分享奖励',
		                    'remark' => "分享成功，奖励0.1元。",
		                    'create_time' => TIMESTAMP
		                ]);
		                
		                message('领取成功','/home/account.html','success');
  			  }
  			
                        
  			
  		}
  	}
  	
  	  	if($type == 'over_task_1'){
  	  		if($member['over_task_1'] == 1){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		
	  		if($member['over_task_1'] < 1 && $member['over_task_num'] >=1 ){
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+1;
	  			$data['over_task_1']=1;
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 1,
			                    'title' => '完成1个任务奖励',
			                    'remark' => "完成1个任务奖励，奖励1元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
            		                
				         	//首次完成任务给上级奖励
				         	if($member['parent_uid']){
				         		
						         	$credit2_dady = 1;
						            $status1 = Member::updateCreditById($member['parent_uid'], 0, $credit2_dady);
						 
						            $status2 = CreditRecord::addInfo([
						                'uid' => $member['parent_uid'],
						                'type' => 'credit2',
						                'num' => $credit2_dady,
						                'title' => '徒弟'.$member['uid'].'首次完成任务奖励',
						                'remark' =>'徒弟'.$member['uid'].'首次完成任务,奖励1元.',
						                'create_time' => TIMESTAMP
						            ]);
						            
						            
						            
						            //添加纪录
			                		InvitationRebateRecord::addInfo([
			                            'uid' => $member['parent_uid'],
			                            'num' => $credit2_dady,
			                            'task_id' => 0,
			                            'tuijian_id' =>$member['uid'],
			                            'remark' => '徒弟'.$member['uid'].'首次完成任务,奖励1元.',
			                            'create_time' => TIMESTAMP
			                        ]);
						            
						            
						            
						            
						            
						            //给上上级的奖励
						            $grandpa=db('member')->find($member['parent_uid']);
						            if($grandpa && $grandpa['parent_uid']){
							         	$credit2_grand = 0.5;
							            $status1 = Member::updateCreditById($grandpa['parent_uid'], 0, $credit2_grand);
							 
							            $status2 = CreditRecord::addInfo([
							                'uid' => $grandpa['parent_uid'],
							                'type' => 'credit2',
							                'num' => $credit2_grand,
							                'title' => '徒孙'.$member['uid'].'首次完成任务奖励',
							                'remark' =>'徒孙'.$member['uid'].'首次完成任务,奖励0.5元.',
							                'create_time' => TIMESTAMP
							            ]);
							            
							            
						            
							            //添加纪录
				                		InvitationRebateRecord::addInfo([
				                            'uid' => $grandpa['parent_uid'],
				                            'num' => $credit2_grand,
				                            'task_id' => 0,
				                            'tuijian_id' =>$member['uid'],
				                            'remark' => '徒孙'.$member['uid'].'首次完成任务,奖励0.5元.',
				                            'create_time' => TIMESTAMP
				                        ]);
							            
							            
							            
						            }
				         	}
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  			
	                        
	  			
	  		}
	  	}
	  	
	  	if($type == 'over_task_3'){
  	  		if($member['over_task_3'] == 1){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		
	  		if($member['over_task_3'] < 1 && $member['over_task_num'] >=3 ){
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+1;
	  			$data['over_task_3']=1;
	  			
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 1,
			                    'title' => '完成3个任务奖励',
			                    'remark' => "完成3个任务奖励，奖励1元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  			
	                        
	  			
	  		}
	  	}
	  	
	  	if($type == 'over_task_8'){
  	  		if($member['over_task_8'] == 1){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		
	  		if($member['over_task_8'] < 1 && $member['over_task_num'] >=8 ){
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+2;
	  			$data['over_task_8']=1;
	  			
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 2,
			                    'title' => '完成8个任务奖励',
			                    'remark' => "完成8个任务奖励，奖励2元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  			
	                        
	  			
	  		}
	  	}

	  	if($type == 'over_task_5'){
	  	
  	  		if($member['over_task_5'] == 1){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		
  	  		if($member['is_share']<1 || $member['over_task_1'] <1 || $member['over_task_3'] <1 || $member['over_task_8'] <1 ){
  	  			 message('请先完成前面的任务','reload','error');
  	  		}
  	  		
  	  		
  	  		
  	  		
  		//有效好友个数
        $down=db('member')->where('parent_uid',$member['uid'])->column('uid');
        $valid_count=db('withdraw')->where(['uid'=>['in',$down]])->count();
        
        
	  		if($member['over_task_5'] < 1 && $valid_count >=5 ){
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+6.66;
	  			$data['over_task_5']=1;
	  			
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 6.66,
			                    'title' => '邀请5个有效好友奖励',
			                    'remark' => "邀请5个有效好友，奖励6.66元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                
			                //完成所有任务奖励
			                
			                
				         	//首次完成任务给上级奖励
				         	if($member['parent_uid']){
				         		
						         	$credit2_dady = 3;
						            $status1 = Member::updateCreditById($member['parent_uid'], 0, $credit2_dady);
						 
						            $status2 = CreditRecord::addInfo([
						                'uid' => $member['parent_uid'],
						                'type' => 'credit2',
						                'num' => $credit2_dady,
						                'title' => '徒弟'.$member['uid'].'完成所有新手任务奖励',
						                'remark' =>'徒弟'.$member['uid'].'完成所有新手任务,奖励你'.$credit2_dady.'元.',
						                'create_time' => TIMESTAMP
						            ]);
						            
						            
						            
						            //添加纪录
			                		InvitationRebateRecord::addInfo([
			                            'uid' => $member['parent_uid'],
			                            'num' => $credit2_dady,
			                            'task_id' => 0,
			                            'tuijian_id' =>$member['uid'],
			                            'remark' => '徒弟'.$member['uid'].'完成所有新手任务,奖'.$credit2_dady.'元.',
			                            'create_time' => TIMESTAMP
			                        ]);
						            
						            
						            //给上上级的奖励
						            $grandpa=db('member')->find($member['parent_uid']);
						            if($grandpa && $grandpa['parent_uid']){
							         	$credit2_grand = 2;
							            $status1 = Member::updateCreditById($grandpa['parent_uid'], 0, $credit2_grand);
							 
							            $status2 = CreditRecord::addInfo([
							                'uid' => $grandpa['parent_uid'],
							                'type' => 'credit2',
							                'num' => $credit2_grand,
							                'title' => '徒孙'.$member['uid'].'完成所有新手任务奖励',
							                'remark' =>'徒孙'.$member['uid'].'完成所有新手任务,奖励你'.$credit2_grand.'元.',
							                'create_time' => TIMESTAMP
							            ]);
							            
							            
						            
							            //添加纪录
				                		InvitationRebateRecord::addInfo([
				                            'uid' => $grandpa['parent_uid'],
				                            'num' => $credit2_grand,
				                            'task_id' => 0,
				                            'tuijian_id' =>$member['uid'],
				                            'remark' => '徒孙'.$member['uid'].'完成所有新手任务,奖励'.$credit2_grand.'元.',
				                            'create_time' => TIMESTAMP
				                        ]);							            
							            

							            
						            }
				         	}
				         	
			                message('领取成功','/home/account.html','success');
	  			  }
	  			
	  		}
	  		
	  		 message('领取失败','reload','error');
	  	}

  }
  
  
  	public function get_nickname($nickname){
		if(!$nickname) return $nickname;
		 $length=floor(strlen($nickname)/2)-3;
		 $nickname=mb_substr($nickname,0,2) . str_repeat('*',$length>0?:0);
		 return $nickname;
		 
	}
	
    //宠物猫
    public function pet(){
        $member = $this->checkLogin();
        $config = Config::getInfo();
		$pet = db('pet')->where('uid',$member['uid'])->find();
        if(request()->isAjax()){
		
            //购买猫宠
            if(input('pet_num') && input('pet_num')>0){
                if($member['credit1']<input('pet_num')*$config['setting']['unit_price']){
            message('积分不足','reload','error');
        }
		        
        //刚领取的猫宠要处理一下，再加两个字段now_day，now_day_pet，预防领取奖励之前领养未过一天直接领奖励
        if($member['pet_num']!=0){
            $data['pet_num'] = $member['pet_num']+input('pet_num');
            $data['credit1'] = $member['credit1']-input('pet_num')*$config['setting']['unit_price'];
            if($member['now_day']==date('Ymd')){
                $data['now_day_pet'] = input('pet_num')+$member['now_day_pet'];
            }else{
                $data['now_day_pet'] = input('pet_num');
                $data['now_day'] = date('Ymd');
            }
            $data['pet_time'] = date('Ymd');
            $data['this_week_pet'] = input('pet_num')+$member['this_week_pet'];
            if($member['pet_time']>0 && $member['first_pet']==1 && $member['pet_time']<date('Ymd')){
		        	$data['first_pet'] = 2;
		        }
            $res = db('member')->where('uid',$member['uid'])->update($data);
        }else{
            $data['credit1'] = $member['credit1']-input('pet_num')*$config['setting']['unit_price'];
            $data['pet_time'] = date('Ymd');
            $data['pet_num'] = input('pet_num');
            $data['now_day'] = date('Ymd');
            $data['now_day_pet'] = input('pet_num');
            $data['this_week_pet'] = input('pet_num')+$member['this_week_pet'];
            if($member['pet_time']>0 && $member['first_pet']==1 && $member['pet_time']<date('Ymd')){
		        	$data['first_pet'] = 2;
		        }
            $res = db('member')->where('uid',$member['uid'])->update($data);
        }
        if($res){
			$pet_data['get_pet_time'] = date('Y-m-d H:i:s');
			$pet_data['get_pet_num'] = input('pet_num');
			if($pet){
				db('pet')->where('uid',$member['uid'])->update($pet_data);
			}else{
				$pet_data['uid'] = $member['uid'];
				db('pet')->insert($pet_data);
			}
            CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit1',
                'num' => -input('pet_num')*$config['setting']['unit_price'],
                'title' => '领养猫宠',
                'remark' => "领养成功，消费".input('pet_num')*$config['setting']['unit_price']."积分。"
            ]);
            message('领养成功','reload','success');
        }else{
            message('领养失败，联系管理','reload','error');
        }
            }else{
            
                 //领取分红
             if($member['pet_num']==0){
                message('抱歉，您没有宠猫','reload','error');
            }
            if($member['pet_num']-$member['now_day_pet']==0){
                message('第二天才可以领取宠猫分红','reload','error');
            }
            if($member['get_pet_jlt']==date('Ymd')){
                message('今日已领取过分红','reload','error');
            }
            $data['get_pet_jlt'] = date('Ymd');
            if($member['pet_points']==0){
            	$data['pet_points'] = $member['pet_num']*$config['setting']['bonus'];
            }else{
            	if($member['now_day']==date('Ymd')){
                	$data['pet_points'] = $member['pet_points']+($member['pet_num']-$member['now_day_pet'])*$config['setting']['bonus'];
            	}else{
                	$data['pet_points'] = $member['pet_points']+$member['pet_num']*$config['setting']['bonus'];
            	}	
            }
            
            if($member['pet_points']==$data['pet_points']){
                message('您还没有可分红的猫宠','reload','error');
            }
            
            
            $res = db('member')->where('uid',$member['uid'])->update($data);
            if($res){
				
				$pet_data['get_point_time'] = date('Y-m-d H:i:s');
				$pet_data['get_pet_point'] = $data['pet_points']-$member['pet_points'];
                $lost_num = intval($pet_data['get_pet_point']/$config['setting']['lost_price']);
                if($lost_num>0){
                    if($lost_num>$member['pet_num']){
                        $lost_num = $member['pet_num'];
                    }
                   
                    $pet_data['point_lost_pet'] = $lost_num;
                    $pet_data['point_lost_pet_time'] = date('Y-m-d H:i:s');
                    
                    db('member')->where('uid',$member['uid'])->setDec('pet_num',$lost_num);
                }
              	unset($pet_data['this_week_pet']);
              $pet_data['now_lj_time'] = date('Ymd');
                  	$pet_data['now_lj_num'] = $member['pet_num']-$member['now_day_pet'];
				if($pet){
                  	$pet_data['pre_lj_time'] = $pet['now_lj_time'];
                  	$pet_data['pre_lj_num'] = $pet['now_lj_num'];
                  	
					db('pet')->where('uid',$member['uid'])->update($pet_data);
				}else{
					$pet_data['uid'] = $member['uid'];
					db('pet')->insert($pet_data);
				}
				
            	CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit2',
                'num' =>$pet_data['get_pet_point'],
                'title' => '领取猫宠分红',
                'remark' => "领取猫宠分红".$pet_data['get_pet_point']."金币",
                'create_time' => TIMESTAMP
            	]);
            	
            	if($member['parent_uid']){
            		$p_level = db('member')->where('uid',$member['parent_uid'])->value('level');
            		if($p_level>1){
            			$invite_rebate = round($pet_data['get_pet_point']*$config['setting']['vip_rebate']/100,2);
            		}else{
            			$invite_rebate = round($pet_data['get_pet_point']*$config['setting']['notinvitation_rebate']/100,2);
            		}
            		CreditRecord::addInfo([
	                'uid' => $member['parent_uid'],
	                'type' => 'credit2',
	                'num' =>$invite_rebate,
	                'title' => '下级猫宠分红奖励'.$member['uid'],
	                'remark' => "下级".$member['uid']."猫宠分红奖励推荐人账户".$invite_rebate."金币",
	                'create_time' => TIMESTAMP
	            ]);
	            $invite_fenhong = db('invite_petfh')->where('uid',$member['uid'])->where('fid',$member['parent_uid'])->find();
	            if($invite_fenhong){
	            	db('invite_petfh')->where('uid',$member['uid'])->where('fid',$member['parent_uid'])->setInc('num',$invite_rebate);
	            }else{
	            	db('invite_petfh')->insert(['uid'=>$member['uid'],'fid'=>$member['parent_uid'],'num'=>$invite_rebate]);
	            }
                  db('member')->where('uid',$member['parent_uid'])->inc('xiaji',$invite_rebate)->inc('pet_points',$invite_rebate)->update(['xiaji_time'=>time()]);
                  
                      //上级的提成
                      $profit_data=[
                        'uid' => $member['uid'],
                        'num'=>$invite_rebate,
                        'remark' => "下级".$member['uid']."猫宠分红奖励推荐人账户".$invite_rebate."金币",
                        'parent_uid' => $member['parent_uid'],
                        'add_time' => date('Ymd'),
                        'create_time'=>time()
                   
                      ];
                        db('profit')->insert($profit_data);
            	}
            	
            	                    //自己的提成
                  $my_profit_data=[
                    'uid' => $member['uid'],
                    'num'=>$pet_data['get_pet_point'],
                    'remark' => '领取宠物猫分红',
                    'parent_uid' => 0,
                    'add_time' => date('Ymd'),
            		'create_time'=>time(),
                  ];
                  db('profit')->insert($my_profit_data);
            	
                message('领取分红成功','reload','success');
            }else{
                message('领取分红失败，联系管理','reload','error');
            }
            }
        }
		if(!$pet){
			$pet['uid'] = 0;
		}
        $result = db('pet_ph')->select();
        $ph = db('member')->where('this_week_pet','>',0)->field('nickname,this_week_pet')->order('this_week_pet DESC')->limit(10)->select();
        foreach ($ph as $key => $value) {
            $ph[$key]['jl'] = $result[$key]['point'];
        }
        if(!empty($pet['pre_lj_time'])){
        	if($pet['pre_lj_time']==date("Ymd",strtotime("-1 day"))){
        		$ysetoday_num = $pet['pre_lj_num'];
        	}else{
        		$ysetoday_num =0;
        	}
        }else{
        	$ysetoday_num =0;
        }
        if($member['first_pet'] == 1){
        	$xiaoshitime = date('Ymd',strtotime($member['pet_time'])+60*60*24*3);
        }else{
        	$xiaoshitime = date('Ymd',strtotime($member['pet_jihua'])+60*60*24*3);
        }
        
        $today_num = $member['pet_num']-$member['now_day_pet'];
        
        //上周的榜单
        $last_week = db('pet_ph')->select();
        
          //今天的分红
        $today=date('Ymd');
        //$today_reward=db('pet')->where(['now_lj_time'=>$today,'uid'=>$member['uid']])->sum('now_lj_num');
        $today_reward=db('profit')->where(['parent_uid'=>$member['uid'],'add_time'=>$today])->sum('num');
        $last_item=db('profit')->where(['parent_uid'=>$member['uid'],'add_time'=>$today])->order('profit_id desc')->limit(1)->find();
        
        //昨日下级提成
        //所有的下级
        $yesterday=date("Ymd",strtotime("-1 day"));

        $down_uids_arr=db('member')->where('parent_uid',$member['uid'])->column('uid');
        $down_uids=implode(',',$down_uids_arr);

        $down_reward=db('profit')->where(['uid'=>['in',$down_uids],'add_time'=>$yesterday,'parent_uid'=>$member['uid']])->sum('num');
        
        
        foreach($last_week as &$v){
        		$v['username']=$this->get_nickname($v['username']);
        }
        
        foreach($ph as &$p){
        		$p['nickname']=$this->get_nickname($p['nickname']);
        }
        
        return $this->fetch(__FUNCTION__,[
            'last_item'=>$last_item,
        	'down_reward'=>$down_reward?:0,
        	 'today_reward'=>$today_reward?:0,
        	'last_week_list'=>$last_week,
            'member' => $member,
			'pet'	=>$pet,
            'ph'    =>$ph,
            'pet_price'=>$config['setting']['unit_price'],
            'pet_bonus'=>$config['setting']['bonus'],
            'pet_need' =>$config['setting']['pet_need'],
            'ysetoday_num'=>$ysetoday_num,
            'today_num'=>$today_num>0?$today_num:0,
            'xiaoshi' =>$member['pet_num']/10>1?floor($member['pet_num']/10):1,
            'xiaoshitime' => $xiaoshitime
        ]);
    }
    //兑换现金
    public function get_money(){
    	$member = $this->checkLogin();
    	
    	
    	if(input('cret_num')<0.1){
    		 message('兑换现金数量必须大于0.1','reload','error');
    	}
    	$cret_nums = input('cret_num')*1000;
    	if($cret_nums>$member['pet_points']){
    		
    		message('金币不足','reload','error');
    	}
    
    	$data['pet_points'] = $member['pet_points']-$cret_nums;
    	$data['credit2'] = $member['credit2']+input('cret_num');
    	$res = db('member')->where('uid',$member['uid'])->update($data);
    	if($res){
    		CreditRecord::addInfo([
	                'uid' => $member['uid'],
	                'type' => 'credit2',
	                'num' =>input('cret_num'),
	                'title' => '金币兑换现金',
	                'remark' => "用户".$member['uid']."金币兑换现金".input('cret_num')."元",
	                'create_time' => TIMESTAMP
	            ]);
	            
	            
    		message('兑换成功','reload','success');
    		
    	}else{
    		message('兑换失败','reload','error');
    	}
    }
    //每周宠物跑定时
    public function pet_lost(){
     	$config = Config::getInfo();
  		$nowday = date('Ymd');
  		//先查出所有的拥有猫宠的
     	$result = db('member')->where('pet_num','>',0)->field('uid,pet_num,pet_time,pet_need_credit,now_day_pet')->select(); 
	    foreach($result as $v){
	     	//如果周末当天有买的，不计数在内
	     	if($v['pet_time'] == $nowday){
	     		$pet_num = $v['pet_num']-$v['now_day_pet'];
	     	}else{
	     		$pet_num = $v['pet_num'];
	     	}
	     	//完不成的做流失宠物处理
		    if($config['setting']['pet_need']*$pet_num>$v['pet_need_credit']){
		        $lost_num = $pet_num/10>1?floor($pet_num/10):1;
		        $data['pet_num'] = $v['pet_num']-$lost_num;
		        //用户宠物表记录开始
		        $pet_info = db('pet')->where('uid',$v['uid'])->find();
		        $pet_data['lost_pet_time'] = date('Y-m-d H:i:s');
		        $pet_data['lost_pet_num'] = $lost_num;
		        if($pet_info){
		       		db('pet')->where('uid',$v['uid'])->update($pet_data);
		      	}else{
		       		$pet_data['uid'] = $v['uid'];
		        db('pet')->insert($pet_data);
		        }
		    }else{
		        //完成的给积攒的宠物所需积分清空，重新计时s
		        $data['pet_need_credit'] = 0; 
		    }
		    //用户宠物表记录结束
		    db('member')->where('uid',$v['uid'])->update($data);
		    unset($data);
		    unset($pet_data);
	    }
	}
  
  
  

   
    //猫宠排行
    public function pet_ph(){
    	$result = db('pet_ph')->select();
        return $this->fetch(__FUNCTION__,[
            'list' => $result
        ]);
    	
    }
  
    //每周统计宠物排行
    public function ac_pet_ph(){
    	//前20名
        $result = db('member')->where('this_week_pet','>',0)->field('nickname,this_week_pet,uid')->order('this_week_pet DESC')->limit(10)->select();
        foreach ($result as $k=> $v) {
            db('pet_ph')->where('id',$k+1)->update(array(
                'username'=>$v['nickname'],
                'num'   =>$v['this_week_pet'],
                'uid'	=>$v['uid']
            ));
        }
        //统计所有的
        $result1 = db('member')->where('this_week_pet','>',0)->field('nickname,this_week_pet,uid')->order('this_week_pet DESC')->select();
        db('all_pet_ph')->where('id','>',0)->delete();
        foreach ($result1 as $k=> $v) {
        	$data['username'] = $v['nickname'];
    		$data['uid']	  = $v['uid'];
    		$data['num']	  = $v['this_week_pet'];
    		db('all_pet_ph')->insert($data);
        }
        
        db('member')->where('this_week_pet','>',0)->setField('this_week_pet',0);
    }
    //我的投注
    public function my_jackpot(){
    	$member = $this->checkLogin();
    	
      	$win_jackpot = db('jackpot')->where('uid',$member['uid'])->where('status',1)->select();
      $win_num = count($win_jackpot);
      $win_jifen = 0;
      $win_jine = 0;
      foreach($win_jackpot as $v){
        $win_jine +=$v['jine'];
      }
        $my_jackpot = db('jackpot')->where('uid',$member['uid'])->order('id desc')->select();
      foreach($my_jackpot as $k=> $v){
      	if($v['today_time'] == date('Ymd')){
        	$my_jackpot[$k]['noday'] = 1;
        }else{
        	$my_jackpot[$k]['noday'] = 0;
        }
      }
      //连续打卡次数
      
        return $this->fetch(__FUNCTION__,[
            'my_jackpot' => $my_jackpot,
          	'win_num'=>$win_num,
          'lianxu'=>$member['lianxudaka'],
          'win_jine'=>$win_jine
        ]);
    }
    //报名任务奖池
    public function jackpot(){
        $member = $this->checkLogin();
        $config = Config::getInfo();
        $all_jackpot = db('all_jackpot')->where('id',1)->find();
        $today_jackpot_num = db('member')->where('partition_status','>',0)->count();
        $today_overtask_num = db('member')->where('partition_status',2)->count();
        $over_num = db('member')->where('partition_status',2)->sum('partition_num');
        $partitions = db('member')->where('partition_status','>',0)->limit(7)->select();
        foreach ($partitions as $key => $value) {
        	$partitions[$key]['face'] = $value['avatar']?'/uploads/'.$value['avatar']:'/static/home/mobile/picture/user.png';
        }
        if(request()->isAjax()){
            if(input('num')<1){
                message('报名数量必须大于0','reload','error');
            }
            if(time()>strtotime(date('Y-m-d 22:00:00'))){
            	message('报名时间已经结束','reload','error');
            }
            if($member['credit2']<input('num')){
            	message('您的金额不足','reload','error');
            }
          	if(input('num')>10){
            	message('最多报名10份','reload','error');
            }
            if($member['partition_status']>0){
                message('报名失败，已经过名','reload','error');
            }else{
                $data['uid'] = $member['uid'];
                $data['num'] = intval(input('num'));
                $data['today_time'] = date('Ymd');
                $res = db('jackpot')->insert($data);
                if($res){
                    db('all_jackpot')->where('id',1)->setInc('num',$data['num']);
                    $member_info['credit2'] = $member['credit2']-$data['num'];
                    $member_info['partition_status'] = 1;
                    $member_info['partition_num'] = 0;
                    db('member')->where('uid',$member['uid'])->update($member_info);
                    CreditRecord::addInfo([
                        'uid' => $member['uid'],
                        'type' => 'credit2',
                        'num' =>-$data['num'],
                        'title' => '报名奖池扣除',
                        'remark' => "报名奖池扣除".$data['num']."元",
                        'create_time' => TIMESTAMP
                    ]);
                    message('报名成功','reload','success');
                }
            }
        }
        $baomingtouxiang = db('jackpot')->field('uid,id')->order('id DESC')->limit(3)->select();
        foreach ($baomingtouxiang as $k=> $v){
            $touxiang = db('member')->where('uid',$v['uid'])->value('avatar');
            $baomingtouxiang[$k]['touxiang'] = $touxiang?$touxiang:'/img/wap.png';
        }
        $taskwhere = ['is_display'=>1,'out_stock_flag'=>0,'is_stop'=>1,'is_dj'=>1];
        $tasks = db('task')->where($taskwhere)->field('id,uid,title,ticket_num,unit_price,join_num')->order('id DESC')->limit(15)->select();
        foreach ($tasks as $k=>$v){
            $touxiang = db('member')->where('uid',$v['uid'])->value('avatar');
            $tasks[$k]['touxiang'] = $touxiang?$touxiang:'/img/wap.png';
        }
        return $this->fetch(__FUNCTION__,[
            'tasks' => $tasks,
            'baomingtouxiang' => $baomingtouxiang,
            'all_jackpot' => $all_jackpot,
            'today_jackpot_num'=>$today_jackpot_num,
            'today_overtask_num'=>$today_overtask_num,
            'over_num'=>$over_num,
            'jc_jine'=>$config['setting']['jc_jine'],
            'jc_maobi'=>$config['setting']['jc_maobi'],
            'partitions'=>$partitions
        ]);
    }
    //每日奖池发奖励
    public function give_jackpot_jl(){
    	$config = Config::getInfo();
        $num = db('all_jackpot')->where('id',1)->value('num');
        $over_num = db('member')->where('partition_status',2)->sum('partition_num');
        $member = db('member')->where('partition_status',2)->field('uid,partition_status,partition_num,dakashijian')->select();
        $one_jackpot = 0;
        $one_jifen = 0;
        if($over_num>0){
        	$one_jackpot = round($num*$config['setting']['jc_jine']/$over_num,2);
	        $one_jifen = round($num*$config['setting']['jc_maobi']/$over_num,2);
	        foreach ($member as $key => $value) {
	            $data['jine'] = $one_jackpot*$value['partition_num'];
	            $data['jifen'] = $one_jifen*$value['partition_num'];
	            $data['status'] = 1;
	            $jackpot = db('jackpot')->where('uid',$value['uid'])->where('today_time',date("Ymd",strtotime("-1 day")))->update($data);
	            db('member')->where('uid',$value['uid'])->inc('credit2',$data['jine'])->inc('credit1',$data['jifen'])->inc('pet_need_credit',$data['jifen'])->update();
	            if($value['dakashijian']==date("Ymd",strtotime("-1 day"))){
	                //连续打卡成功
	                db('member')->where('uid',$value['uid'])->setInc('lianxudaka');
	            }else{
	                db('member')->where('uid',$value['uid'])->setField('lianxudaka',1);
	            }
	            db('member')->where('uid',$value['uid'])->setField('dakashijian',date('Ymd'));
	            CreditRecord::addInfo([
	                        'uid' => $value['uid'],
	                        'type' => 'credit2',
	                        'num' =>$data['jine'],
	                        'title' => '奖池分红',
	                        'remark' => "奖池分红增加".$data['jine']."元",
	                        'create_time' => TIMESTAMP
	                    ]);
	            CreditRecord::addInfo([
	                'uid' => $value['uid'],
	                'type' => 'credit1',
	                'num' => $data['jifen'],
	                'title' => '奖池分红',
	                'remark' => "奖池分红增加".$data['jifen']."积分。"
	            ]);
	        }
        }
        //发完奖励初始化报名
        $member_data['partition_status']=0;
        $member_data['partition_num']=0;
        $member_data['now_day_pet']=0;
        
        db('member')->where('partition_status','>',0)->update($member_data);
        $all_jackpot_data['ysetoday_num'] = $num;
        $all_jackpot_data['overnum'] = $over_num;
        $all_jackpot_data['one_jackpot'] = $one_jackpot;
        $all_jackpot_data['one_jifen'] = $one_jifen;
        $all_jackpot_data['num'] = 0;
        db('all_jackpot')->where('id',1)->update($all_jackpot_data);
    }
    //聊天沟通列表
    public function chatlist(){
    	$member = $this->checkLogin();
    	$list = db('chat')->where('sid|uid',$member['uid'])->order('create_time desc')->select();
    	return $this->fetch(__FUNCTION__,[
            'list' => $list,
            'uid'=> $member['uid']
        ]);
    }
    
    
    
    //聊天详细数据
    public function chatinfo(){
        $member = $this->checkLogin();
        $current_user_id=$member['uid'];
        $task_id=input('task_id');
        $cid=input('cid');

        $id=$receiver_name='';
        $chatinfo=$list=[];
        if($task_id){
            $task_info=db('task')->find($task_id);
            //是否是雇主
            if($task_info['uid'] == $member['uid']){
                //雇主
                $chat_where=[
                    'task_id'=>$task_id,
                    'sid'=>$member['uid'],   //发布者
                    'uid'=>input('uid')   //赚客
                ];
                $chatinfo=db('chat')->where($chat_where)->find();

                $receiver_name=db('member')->where('uid',input('uid'))->value('nickname');

            }else{
                //赚客
                $chat_where=[
                    'task_id'=>$task_id,
                    'sid'=>$task_info['uid'],   //发布者
                    'uid'=>$member['uid']   //赚客
                ];
                $chatinfo=db('chat')->where($chat_where)->find();
                $receiver_name=db('member')->where('uid',$task_info['uid'])->value('nickname');
            }

            if($chatinfo){
                $cid=$chatinfo['id'];
            }
        }

        if($cid){

            $chatinfo = db('chat')->where('id',$cid)->find();

            $task_id=$chatinfo['task_id'];

            if($member['uid'] == $chatinfo['sid']){
                    //雇主
                        //商家回复给用户增加未查看消息
                        db('member')->where('uid',$member['uid'])->setDec('chat_num',$chatinfo['snum']);

                        db('chat')->where('id',$cid)->setField('snum',0);
                        $receiver_name=db('member')->where('uid',$chatinfo['uid'])->value('nickname');
                    }else{
                        //接单者回复，给商家加未查看消息
                        db('member')->where('uid',$member['uid'])->setDec('chat_num',$chatinfo['unum']);
                        db('chat')->where('id',$cid)->setField('unum',0);
                        $receiver_name=db('member')->where('uid',$chatinfo['sid'])->value('nickname');
                    }
            $list = db('chat_reply')->where('cid',$cid)->select();
        }

        if(request()->isAjax()){
            if(!$chatinfo){
                message('留言不存在，不可发起回复','reload','error');
            }
            if($chatinfo['sid'] != $member['uid'] && $chatinfo['uid'] != $member['uid']){
                message('请勿回复与自己无关的留言','reload','error');
            }
            $avatar='http://wap.Wacp.top/static/home/mobile/login/img3.png';
            $data['task_id']  = $chatinfo['task_id'];
            $data['cid']      = $cid;
            $data['content']  = input('content');
            $data['img']      = input('img');
            $data['uid']      = $member['uid'];
            $data['nickname'] = $member['nickname'];
            $data['avatar']   = $member['avatar']?:$avatar;
            $res = db('chat_reply')->insert($data);
            if($res){
                if($member['uid'] == $chatinfo['sid']){
                    //商家回复给用户增加未查看消息
                    db('member')->where('uid',$chatinfo['uid'])->setInc('chat_num');
                    db('chat')->where('id',$chatinfo['id'])->setInc('unum');
                }else{
                    //接单者回复，给商家加未查看消息
                    db('member')->where('uid',$chatinfo['sid'])->setInc('chat_num');
                    db('chat')->where('id',$chatinfo['id'])->setInc('snum');
                }
                message('回复成功','reload','success');
            }else{
                message('回复失败，联系管理','reload','error');
            }
        }

        $chatinfo['receiver_name']=$receiver_name;

            $datas=[];
        if($list){
            $chat_model=db('chat_reply');
            foreach($list as $v){
                if($v['parent_id']){
                    continue;
                }
                $d=$v;
                $d['adminMsg']=$chat_model->where('parent_id',$v['id'])->select();
                $datas[]=$d;
            }
        }
        
        return $this->fetch(__FUNCTION__,[
            'list' => $datas?:$list,
           // 'cid'  => input('id'),
            'cid'  => $cid,
            'tid'  => $task_id,
            'uid'  => input('uid'),
            'chat' => $chatinfo,
            'current_user_id'=>$current_user_id
        ]);
    }




    
    //聊天详细数据
    public function groupchat(){
        $member = $this->checkLogin();
        
        $user_id=$member['uid'];

        if(request()->isAjax()){

            $avatar='https://wap.Wacp.top/static/home/mobile/login/img3.png';
           
  
            $data['content']  = input('content');
            $data['img']      = input('img');
           
            if(!$data['content'] && !$data['img']){
                message('请输入留言内容','','error');
            }
            
            $data['uid']      = $member['uid'];
            $data['nickname'] = $member['nickname'];
            $data['avatar']   = $member['avatar']?:$avatar;
            $data['create_time']=time();
            
            $res = db('groupchat')->insert($data);
            
            $last_id=db('groupchat')->max('id');
            
            header('content-type:application/json;charset=utf8');
                    
            if($res){
            	exit(json_encode([
						'type'=>'success',            	
						'msg'=>'回复成功',
						'last_id'=>$last_id,
						
            	]));
               // message('回复成功','','success');
            
            	
            }else{
            	exit(json_encode([
						'type'=>'fail',            	
						'msg'=>'失败',
						'last_id'=>$last_id,
            	]));

               // message('回复失败，联系管理','','error');

            }
        }

//		$list=db('groupchat')->alias('a')->limit(20)->join('member b','a.uid = b.uid')->select();
		
		$list=db('groupchat')->limit(20)->order('id desc')->select();
		$last_id=db('groupchat')->max('id');
		
		 foreach($list as &$v){
			
			$v['create_time']=date('Y-m-d H:i:s',$v['create_time']);
		 
		 }
		 	krsort($list);

        return $this->fetch(__FUNCTION__,[
            'list' => $list,
            'current_user_id'  => $user_id,
            'member'=>$member,
            'last_id'=>$last_id
        ]);
    }



	public function get_message(){
		$member = $this->checkLogin();
		$user_id=$member['uid'];
		 $last_id=input('last_id');
	     if(!$last_id){
            message('无更新','','error');
        }
		$list=db('groupchat')->where(['id'=>['gt',$last_id]])->select();
		 
		$last_id=db('groupchat')->max('id');
		
        $content=$this->fetch(__FUNCTION__,[
            'list' => $list,
            'current_user_id'  => $user_id,
            'member'=>$member,
            'last_id'=>$last_id
        ]);

		 foreach($list as &$v){
			
			$v['create_time']=date('Y-m-d H:i:s',$v['create_time']);
		 
		 }
		 
            if($content){
            	exit(json_encode([
						'type'=>'success',            	
						'msg'=>'获取成功',
						'content'=>$content,
						'last_id'=>$last_id,
						
            	]));
               // message('回复成功','','success');
            
            }else{
            	exit(json_encode([
						'type'=>'fail',            	
						'msg'=>'失败',
						'last_id'=>$last_id,
            	]));

               // message('回复失败，联系管理','','error');
            }
        
		
	}


         //发起客服留言
    public function addchat(){
        if(request()->isAjax()){
            $member = $this->checkLogin();
            $task_id=input('task_id');
            $task_info    = db('task')->where('id',$task_id)->find();
            if(empty($task_info)){
                message('单子已删除','reload','error');
            }
            $boss_id=$task_info['uid'];

            $member_model=db('member');
            $boss_info=$member_model->find($boss_id);

            //是否是雇主
                $is_boss=false;
                if($member['uid'] == $task_info['uid']){
                    $is_boss=true;
                }

                //接单者的id
                $uid='';

            //判断是否已接单
                $task_join=[];


                if($is_boss){
                    $uid=input('uid');

                }else{
                    $uid=$member['uid'];
                }
                if(!$uid){
                    message('系统错误','reload','error');
                }
                //赚客的信息
                $member_info=$member_model->find($uid);

                $task_join = db('task_join')->where('uid',$uid)->where('task_id',$task_id)->find();
            if(!$task_join){
                    message('未接单不可发起留言','reload','error');
            }

            $chatinfo = db('chat')->where('uid',$uid)->where('task_id',$task_id)->find();

            if($chatinfo){
                message('已有留言，如需回复请前往留言列表查看','reload','error');
            }

            //要有两条记录
            $data['task_id']  = $task_id;
            $data['content']  = input('content');
            $data['img']      = input('img');
            $data['sid']      = $boss_id;  //任务发布者id
            $data['uid']      = $uid;   //接收任务者的id
            $data['nickname'] = $boss_info['nickname'];   //雇主的昵称
            $data['user_nickname'] = $member_info['nickname'];   //赚客的昵称
            $data['avatar']   = $boss_info['avatar']; //雇主的头像
            $data['user_avatar']   = $member_info['avatar'];  //赚客的头像
            $data['title']    = $task_info['title'];
            $chat_model=db('chat');

            $res = $chat_model->insert($data);

            $cid=$chat_model->getLastInsID();

            if($cid){
                $chat_data['task_id']  =$task_id;
                $chat_data['cid']      = $cid;
                $chat_data['content']  = input('content');
                $chat_data['img']      = input('img');
                $chat_data['uid']      = $member['uid'];
                $chat_data['nickname'] = $member['nickname'];
                $chat_data['avatar']   = $member['avatar'];

                db('chat_reply')->insert($chat_data);
            }

            if($res){
                db('member')->where('uid',$data['sid'])->setInc('chat_num');
                message('留言成功','reload','success');
            }else{
                message('留言失败，联系管理','reload','error');
            }
        }

    }
    
    
        public function report(){
	        $member=$this->checkLogin();
	        $cid=request()->param('cid');
	        if(!$cid){
	                message('参数错误','reload','error');
	
	        }
	        $where=[
	            'id'=>$cid,
	        ];
	
	        $rst=db('chat')->where($where)->setField('status',2);
	        if($rst){
	               message('举报成功','reload','success');
	        }else{
	            message('举报失败','reload','error');
	        }
	
	    }
	    public function test_sms(){
	    	$sms = new \alisms\SendSms();
	        $sms->accessKeyId = 'LTAI4G3AimiX8W39ZRXhDizV';
	        $sms->accessKeySecret = 'IZqtIIN6kx3sIE6s6bSexsOuhTvNcd';
	        $sms->signName = '闲猫网络';
	        $sms->templateCode = 'SMS_189711724';
	        $templateParam = array("name" => 123);
	        $m = $sms->send(18639022820, $templateParam);
	        var_dump($m);
	    }
	    //用户申诉
    public function complaint(){
      $member = $this->checkLogin();
      $compinfo = db('complaint')->where('uid|fid',$member['uid'])->where('join_id',input('id'))->find();
      if($compinfo){
      	$complaint_info_reply = db('complaint_reply')->where('tid',$compinfo['id'])->select();
      	if($member['uid'] == $compinfo['uid']){
	    	$otherinfo = db('member')->where('uid',$compinfo['fid'])->find();
	    }else{
	    	$otherinfo = db('member')->where('uid',$compinfo['uid'])->find();
	    }
      	
      }else{
      	$complaint_info_reply = '';
      	$otherinfo = [];
      }
      
      if(request()->isAjax()){
      //如果没开启就进来开启申诉，有的话就读取数据
      if(!$compinfo){
      	$my_task_join = db('task_join')
        ->where('id',input('id'))
        ->where('status',4)
        ->find();
        if(empty($my_task_join)){
          message('任务不符合申诉要求','','error');
        }
        $task_info = \app\home\model\Task::getInfoById($my_task_join['task_id']);
        if(empty($task_info)){
            message('任务不存在1','','error');
        }
        //时间不对也算不存在
        if ($task_info['start_time'] > TIMESTAMP || $task_info['origin_end_time'] < TIMESTAMP) {
            message('任务不存在','','error');
        }
        if($task_info['out_stock_flag'] == 1 ){
          message('任务已下架，不可申诉','','error');
        }
        if($member['uid'] !=$task_info['uid'] && $member['uid'] != $my_task_join['uid']){
        	message('与任务无关的用户不可申诉','','error');
        }
        if(input('img')=='' && input('content')==''){
	          message('请提供依据','','error');
	    }
	    //雇主投诉
	    if($member['uid'] == $task_info['uid']){
	    	$data['type'] = 2;
	    	$data['fid']     = $my_task_join['uid'];
	    	$other_info = db('member')->where('uid',$my_task_join['uid'])->find();
	    }else{
	    	$data['fid']     = $task_info['uid'];
	    	$other_info = db('member')->where('uid',$task_info['uid'])->find();
	    }
	   
        //组装数据
        $data['uid']     = $member['uid'];
        $data['tname']     = $member['nickname'];
        $data['rname']     = $task_info['title'];
        $data['btname']     = $other_info['nickname'];
        $data['task_id'] = $my_task_join['task_id'];
        $data['join_id'] = input('id');
        $data['over_time'] = time()+86400;
        $res = db('complaint')->insertGetId($data);
        db('task_join')->where('id',input('id'))->setField('is_shensu',1);
        $reply['uid']     = $member['uid'];
	    $reply['tid']     = $res;
	    $reply['content'] = input('content');
	    $reply['img']	  = input('img');
	    $res2 = db('complaint_reply')->insert($reply);
        if($res && $res2){
        	//给对方发短信
        	$mobile = db('member')->where('uid',$data['fid'])->value('username');
        	$sms = new \alisms\SendSms();
	        $sms->accessKeyId = 'LTAI4FxGJNP3w2DS3U1hE8o6';
	        $sms->accessKeySecret = 'TJNNiCVcujgvGBYzeC4gGjdT3lLPZ9';
	        $sms->signName = '寻小葱';
	        $sms->templateCode = 'SMS_182677208';
	        $templateParam = array("name" => $task_info['id']);
	        $m = $sms->send($mobile, $templateParam);
        	
          message('开启申诉成功','reload','success');
        }else{
          message('开启申诉失败，联系管理员','','error');
        }
      }else{
    	//开始尬聊
	        if(input('img')=='' && input('content')==''){
	          message('请提供依据','','error');
	        }
	        if($compinfo['status'] != 0){
	          message('申诉已结束','','error');
	        }
	        //组装数据
	        $data['uid']     = $member['uid'];
	        $data['tid']     = $compinfo['id'];
	        $data['content'] = input('content');
	        $data['img']	 = input('img');
	        $res = db('complaint_reply')->insert($data);
	        if($res){
	          message('成功','reload','success');
	        }else{
	          message('失败，联系管理员','','error');
	        }
    	}
      }
      return $this->fetch(__FUNCTION__,[  
      		'member'   => $member,
            'compinfo' => $compinfo,
            'complaint_info_reply' => $complaint_info_reply,
            'id' => input('id'),
            'otherinfo' => $otherinfo
        ]);
    }
    //投诉列表
    public function complaintlist(){
    	$member = $this->checkLogin();
    		$list = db('complaint')->where('uid',$member['uid'])->select();
    		foreach ($list as $k=> $v){
    			$list[$k]['avatar'] = db('member')->where('uid',$v['fid'])->value('avatar');
    		}
    	return $this->fetch(__FUNCTION__,[
    		'member'   => $member,
            'list' => $list
        ]);
    }
    //被投诉列表
    public function complaintlist2(){
    	$member = $this->checkLogin();
    		$list = db('complaint')->where('fid',$member['uid'])->select();
    		foreach ($list as $k=> $v){
    			$list[$k]['avatar'] = db('member')->where('uid',$v['uid'])->value('avatar');
    		}
    	return $this->fetch(__FUNCTION__,[
    		'member'   => $member,
            'list' => $list
        ]);
    }
    //投诉通过
    public function passcomplaint(){
    	$member = $this->checkLogin();
    	$complaint_info = db('complaint')->where('id',input('id'))->find();
    	$task_info = db('task')->where('id',$complaint_info['task_id'])->find();
    	if($complaint_info['status'] != 0){
    		message("已经裁决的不可更改",'reload','error');
    	}
    	db()->startTrans();
    	if($complaint_info['type']==2){
    		die;
    	}
    	if($complaint_info['fid'] != $member['uid']){
    		die;
    	}
    	//更改投诉状态
    	$complaint_data['status'] = 1;
    	$complaint_data['over_time'] = time();
    	$complaint_res = db('complaint')->where('id',input('id'))->update($complaint_data);
    	//赚客投诉成功，用户加钱、积分、猫宠所需积分，免费会员完成任务度以及打卡
	    	$userinfo = db('member')->where('uid',$complaint_info['uid'])->find();
	    	if($userinfo['partition_status']==1){
		            $jackpot = db('jackpot')->where('uid',$userinfo['uid'])->where('today_time',date('Ymd'))->find();
		            if($jackpot['num']>$userinfo['partition_num']){
		                $member_data['partition_num'] = $userinfo['partition_num']+1;
		            }
		            if($jackpot['num']==$userinfo['partition_num']+1){
		                	$member_data['partition_status']=2;
		            }
		    }
		    $member_data['over_task_num'] = $userinfo['over_task_num']+1;
		    $member_data['credit2'] = $userinfo['credit2']+$task_info['unit_price'];
		    if($task_info['give_credit1']>0){
		    	$member_data['pet_need_credit'] = $userinfo['pet_need_credit']+$task_info['give_credit1'];
	        	$member_data['credit1'] = $userinfo['credit1']+$task_info['give_credit1'];
		    }
		    $member_res = db('member')->where('uid',$userinfo['uid'])->update($member_data);
		    if($task_info['unit_price']>0){
		    	 CreditRecord::addInfo([
                'uid' => $userinfo['uid'],
                'type' => 'credit2',
                'num' => $task_info['unit_price'],
                'title' => '审核任务',
                'remark' => "任务" . $complaint_info['task_id'] . "审核成功，奖励".$task_info['unit_price']."元。",
                'create_time' => TIMESTAMP
            ]);
		    }
		    if($task_info['give_credit1']>0){
		    	 CreditRecord::addInfo([
                'uid' => $userinfo['uid'],
                'type' => 'credit1',
                'num' => $task_info['give_credit1'],
                'title' => '审核任务',
                'remark' => "任务" . $complaint_info['task_id'] . "审核成功，奖励".$task_info['give_credit1']."积分。",
                'create_time' => TIMESTAMP
            ]);
		    }
		   
		    //任务状态设置成完成，申诉解除
		    $task_join_data['status'] = 3;
		    $task_join_data['is_shensu'] = 0;
		    $task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
		    //明天把助手函数事物搞上去
		    if($complaint_res && $member_res && $task_join_res){
		    	
		//给上级和上上级发奖励
		
		task_reward($userinfo,$task_info);
		
		//发红包
		$params['id']=$complaint_info['task_id'];
		$joinInfo['uid']=$userinfo['uid'];

		$redpackage=\db('redpackage')->where(['task_id'=>$params['id']])->find();

		if($redpackage && !$redpackage['is_over']){
				$has_send_money=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->sum('money');
				$has_send_number=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->count();
	
				if($has_send_money <$redpackage['money']){
					
					//要发的红包
					$send_info=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['eq',0]])->order('redpackage_record_id asc')->find();
					
					$left_money=$redpackage['money']-$has_send_money;

					if($send_info && $left_money>0){
						
							//是否最后一个用户
							if( ($has_send_number+1) == $redpackage['number'] ){
								\db('redpackage')->where(['task_id'=>$params['id']])->setField('is_over',1);
							}
							
							$get_money=$send_info['money'];
							
					
							
						     $credit2 = $userinfo['credit2']+$get_money;
					    
					       // $res1 = \db('member')->where(['uid'=>$joinInfo['uid']])->data(['credit2'=>$credit2])->update();
					          
					          $res1 = Member::updateCreditById($joinInfo['uid'], 0, $get_money);
					          
					            if(!$res1){
						            Db::rollback();
						            message('操作失败:-3','','error');
						        }
		
		
					        $creditdata = array(
					            'uid'=>$joinInfo['uid'],
					            'type'=>'credit2',
					            'num'=>'+'.$get_money,
					            'title'=>'完成任务获得红包',
					            'remark'=>'完成任务'.$params['id'].'获得红包'.$get_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
					            message('审核失败:-5','','error');
					        }
					        
					        $send_info['uid']=$joinInfo['uid'];
					        $send_info['add_time']=time();
					        
					       $res4 = \db('redpackage_record')->data($send_info)->update();
					        if(!$res4){
					            Db::rollback();
					            message('审核失败:-6','','error');
					        }
					}
				        
				        
				        
				}
			        
		
		}
		
		
		
		
		
		
		    	
		    	
		    	
		    	
		    	
		    	db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    }
    //撤诉
    public function backcomplaint(){
    	$member = $this->checkLogin();
    	$complaint_info = db('complaint')->where('id',input('id'))->find();
    	if($complaint_info['status'] != 0){
    		message("已经裁决的不可更改",'reload','error');
    	}
    	if($complaint_info['uid'] != $member['uid']){
    		die;
    	}
    	$task_info = db('task')->where('id',$complaint_info['task_id'])->find();
    	db()->startTrans();
    	//投诉状态改为撤诉
    	$complaint_data['status'] = 4;
    	$complaint_data['over_time'] = time();
    	$complaint_res = db('complaint')->where('id',input('id'))->update($complaint_data);
    	if($complaint_info['type'] == 1){
    		//赚客撤诉
    		//任务状态设置成未完成，申诉解除,设置已返还
		    $task_join_data['status'] = 4;
		    $task_join_data['delflag'] = 2;
		    $task_join_data['is_fanhuan'] = 1;
		    $task_join_data['is_shensu'] = 0;
		    $task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
		    //给雇主把已加入票数减去1
		    $task_res = db('task')->where('id',$complaint_info['task_id'])->setDec('join_num');
		    //明天把助手函数事物搞上去
		    if($complaint_res && $task_res && $task_join_res){
		    	db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    	}else{
    		$task_join_data['is_shensu'] = 0;
		    $task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
    		if($complaint_res){
		    	db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    	}
    }
   
   

    public function weekly_ajax(){

      $request=request();
      $page=$request->param('page');
        $start=10*($page-1);

	
	    
		$this_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
			
	        $this_week=strtotime($this_monday);
	        $where=[
	          'a.create_time'=>['gt',$this_week],
	          'status'=>3
	        ];
	        
	        
	        $list=db('task_join')->alias('a')->field("count(a.id) as count,a.uid,b.nickname,sum(unit_price) as total_price")->join('member b','a.uid=b.uid')->join('task c',' a.task_id=c.id')->group('a.uid')->order('count desc,total_price desc')->where($where)->limit(30)->select();
	  
		$task_weekly=db('task_weekly')->where('num','>',0)->select();

		foreach($task_weekly as $k => &$v){
			if(isset($list[$k])){
		
				$v['nickname']=$this->get_nickname($list[$k]['nickname']);
				$v['total_price']=$list[$k]['total_price'];
				$v['count']=$list[$k]['count'];
				$v['uid']=$list[$k]['uid'];
			}else{
				$v['nickname']='';
				$v['total_price']='';
				$v['count']=0;
				$v['uid']=0;
			}
			
		}


		 	if(request()->isAjax()){
		        return $this->fetch(__FUNCTION__, [
		            'list'=>array_slice($task_weekly,$start,10),
		          ]);
		 	}else{
		 		return $task_weekly;
		 	}

    }   
   
     //发放奖励
     public function send_weekly_reward(){
     
     	$task_weekly=$this->weekly_ajax();
     	
     	$this_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
     	
     	$weekly_record_model=db('weekly_record');
     
     	foreach($task_weekly as $k=>$v){
     		if($v['uid']>0 && $v['num']>0){
     		
            	Db::startTrans();
          
	             $status1 = Member::updateCreditById($v['uid'], 0, $v['num']);
	     
	             if(!$status1){
	                 Db::rollback();
	             }
	            
	            
	            //记录奖励操作
	            $status2 = CreditRecord::addInfo([
	                'uid' => $v['uid'],
	                'type' => 'credit2',
	                'num' => $v['num'],
	                'title' => '每周之星奖励',
	                'remark' => "获得每周之星排行榜第".$v['task_weekly_id']."名，奖励：" . $v['num']."元。",
	                'create_time' => TIMESTAMP
	            ]);
	          
	      
	            if(!$status2){
	                Db::rollback();
	            }
	            $insert_data=[
	            		'uid'=>$v['uid'],
	            		'num' => $v['num'],
	            		'count' => $v['count'],
	            		'task_weekly_id' => $v['task_weekly_id'],
	            		'reward_time'=>$this_monday,
	            	];
	            
            	$weekly_record_model->insert($insert_data);
            	
            	Db::commit();
            
     		}
     	}
     	
     }
   
    //邀请好友排行榜作弊
    
    function invite_cheat(){
        //作弊功能
	      $config = Db::name('config')->find();
	      $setting = unserialize($config['setting']);
	
	      if(!empty($setting['special_user']) && !empty($setting['range'])){
	
	        $users=$setting['special_user'];
	        $range=$setting['range'];
	        $users_arr=explode(',',$users);
	        $range_arr=explode('@',$range);
	        $record_model=db('invitation_rebate_record');
	
	       // db('member')->where('uid',7)->setField('create_time',TIMESTAMP);
	       
	        foreach($users_arr as $k=>$v){
	            $int_arr=explode(',',$range_arr[$k]);
        		$int=rand($int_arr[0],$int_arr[1]);
	            $float=rand(0,10)/10+rand(0,10)/100;
	            $num=$int+$float;
	        
	            $add_data=[
	              'uid'=>$v,
	              'num'=>$num,
	              'task_id'=>'',
	              'tuijian_id'=>11020,
	              'remark'=>'推荐下级'.$v.'首单提现奖励'.$num.'元',
	              'create_time'=>TIMESTAMP,
	            ];
	      
	          $record_model->insert($add_data);
	        }
	      }
	      
	      
	      
	      //缓存邀请好友数据
	      

		  $config = Db::name('config')->find();
        $config['setting'] = unserialize($config['setting']);
        
        $invite_start_time = $config['setting']['invite_start_time'];
        $invite_end_time = $config['setting']['invite_end_time'];
	        

	      $invite_start_time_str=strtotime($invite_start_time);
	       $invite_end_time_str=strtotime($invite_end_time);
	        
	        $rebate_where=[
	          'a.create_time'=>['gt',$invite_start_time_str],
	          'c.create_time'=>['gt',$invite_start_time_str],
	          
	           'a.create_time'=>['lt',$invite_end_time_str],
	          'c.create_time'=>['lt',$invite_end_time_str],
	          
	          
	        ];
	        
	        $list=db('invitation_rebate_record')->alias('a')->field("sum(num) as num,a.uid,b.nickname")->join('member b','a.uid=b.uid')->join('member c','a.tuijian_id=c.uid')->group('a.uid')->order('num desc,a.uid asc')->where($rebate_where)->limit(100)->select();
	        $reward=db('reward')->where(['num'=>['gt',0]])->select();
	

	
	        //前三名
	        $one=$two=$three=[];
	        //第一名
	
	        $one_arr=array_shift($list);

	        $on_rank=0;
	        $one_reward_arr=array_shift($reward);
	        if($one_arr['num']>$one_reward_arr['min']){
	        
	          $one=[
	            'ranking'=>1,
	            'uid'=>$one_arr['uid'],
	            'nickname'=>$this->get_nickname($one_arr['nickname']),
	            'reward'=>$one_reward_arr['num'],
	            'num'=>$one_arr['num'],
	          ];
	          $on_rank+=1;
	
	        }else{
	        
	          $one=[
	          'ranking'=>1,
	            'uid'=>'',
	            'nickname'=>'暂无上榜',
	            'reward'=>$one_reward_arr['num'],
	            'num'=>$one_reward_arr['min'],
	          ];
	
	          $list=array_merge([$one_arr],$list);
	
	          array_pop($list);
	        }
	
	
	
	        //第二名
	        $two_arr=array_shift($list);
	        $two_reward_arr=array_shift($reward);
	        if($two_arr['num']>$two_reward_arr['min']){
	          $two=[
	            'ranking'=>2,
	            'uid'=>$two_arr['uid'],
	            'nickname'=>$this->get_nickname($two_arr['nickname']),
	            'reward'=>$two_reward_arr['num'],
	            'num'=>$two_arr['num'],
	          ];
	          $on_rank+=1;
	        }else{
	          $two=[
	            'ranking'=>2,
	            'uid'=>'',
	            'nickname'=>'暂无上榜',
	            'reward'=>$two_reward_arr['num'],
	            'num'=>$two_reward_arr['min'],
	          ];
	
	          $list=array_merge([$two_arr],$list);
	          array_pop($list);
	        }
	
	        //第三名
	        $three_arr=array_shift($list);
	        $three_reward_arr=array_shift($reward);
	        if($three_arr['num']>$three_reward_arr['min']){
	          $three=[
	            'ranking'=>3,
	            'uid'=>$three_arr['uid'],
	            'nickname'=>$this->get_nickname($three_arr['nickname']),
	            'reward'=>$three_reward_arr['num'],
	            'num'=>$three_arr['num'],
	          ];
	          $on_rank+=1;
	        }else{
	          $three=[
	            'ranking'=>3,
	            'uid'=>'',
	            'nickname'=>'暂无上榜',
	            'reward'=>$three_reward_arr['num'],
	            'num'=>$three_reward_arr['min'],
	          ];
	
	           $list=array_merge([$one_arr],$list);
	           array_pop($list);
	        }
		
	
			$rank=[];
			$rank[0]=$one;
			$rank[1]=$two;
			$rank[2]=$three;
	        $rank_num=4;
	        
	        foreach($list as $k=> $v){
	            $d=[];
	            $d['ranking']=$rank_num;
	            $d['uid']=$v['uid'];
	            $d['num']=$v['num'];
	            
	            $d['nickname']=$this->get_nickname($v['nickname']);
	            
	            
	            $d['reward']=$reward[$k]['num'];
	            
	            $rank[]=$d;
	            $rank_num+=1;
	            
	            unset($reward[$k]);
	        }
	        

	        foreach($reward as $k=> $v){
	            $d=[];
	            $d['ranking']=$rank_num;
	            $d['uid']='';
	            $d['num']=$v['min'];
	            $d['nickname']='';
	            $d['reward']=$reward[$k]['num'];
	            $rank[]=$d;
	            $rank_num+=1;
	            unset($reward[$k]);
	        }	      
	      
	      Cache::set('rank_ajax_data',json_encode($rank),3600);
	      
	      
	      
	      
	      
	      
    }
}















